/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package core.connector.email.http.gazeta;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpression;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;

import core.connector.ConnectionDetails;
import core.connector.email.http.gmail.HttpConnectorGmail;
import core.util.JGoogleAnalytics;
import core.xml.XPathNavigation;

/**
 *
 * @author Vinicius
 */
public class HttpConnectorGazeta extends HttpConnectorGmail{


    private XPathExpression inputBackPath;
    private XPathExpression inputBack2Path;
    private XPathExpression formActionPath;

    public HttpConnectorGazeta(ConnectionDetails connectionDetails){
        super(connectionDetails);
        int index;
        if(connectionDetails.getLogin() != null && ((index = connectionDetails.getLogin().trim().indexOf("@gazeta.pl")) > -1)){
            String login = connectionDetails.getLogin().substring(0,index);
            connectionDetails.setLogin(login);
            this.user = login;
        }
        JGoogleAnalytics.trackAsynchronously("Connector HTTP - GAZETA.PL-MAIL");
    }

    {
        try {
            inputBackPath = xpath.compile("//form[@id='loginForm']/input[@name='back']/@value");
            inputBack2Path = xpath.compile("//form[@id='loginForm']/input[@name='back2']/@value");
            formActionPath = xpath.compile("//form[@id='loginForm']/@action");            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean connect() {
        System.out.println("CONECTANDO...");
        if (user.equals("") || passwd.equals(""))
        {
            throw new IllegalStateException("Cannot connect: user and password not specified.");
        }

        clearCookie();
        
        String loginAction;
        String back;
        String back2;

        GetMethod get = new GetMethod("https://www.google.com/a/gazeta.pl/ServiceLogin?service=mail");
        get.addRequestHeader("Accept", "text/html");
        get.addRequestHeader("Connection", "keep-alive");
        get.addRequestHeader("Accept-Encoding","gzip");
        setCookies(get);

        String resultado;
        try{
            client.executeMethod(get);
            resultado = getResponseBodyAsString(get);
            Header[] cookies = get.getResponseHeaders("set-cookie");
            for(Header cookie : cookies){
                buildCookie(cookie);
            }
        }catch(Exception ex){
            ex.printStackTrace();
            return false;
        }

        Document dom = null;

        TagNode root = getCleaner().clean(resultado);
        try {
            dom = getDomSerializer().createDOM(root);
        } catch (ParserConfigurationException ex) {
            ex.printStackTrace();
        }

        XPathNavigation nav = new XPathNavigation(dom);
        back = nav.getXpathPropertyUtil(inputBackPath).getAttributeValue();
        back2 = nav.getXpathPropertyUtil(inputBack2Path).getAttributeValue();
        loginAction = nav.getXpathPropertyUtil(formActionPath).getAttributeValue();


        PostMethod post = new PostMethod("http://auth.gazeta.pl"+loginAction);
        post.addRequestHeader("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png;q=0.5");
        post.addRequestHeader("Connection", "keep-alive");
        post.addRequestHeader("Accept-Encoding", "gzip");
        post.addRequestHeader("Referer", "http://auth.gazeta.pl/googleAuth/"+back);
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        post.addParameter("back", back);
        post.addParameter("back2", back2);
        post.addParameter("Login", "1");
        post.addParameter("username", user);
        post.addParameter("password", passwd);
        setCookies(post);

        try
        {
            post.setFollowRedirects(false);
            client.executeMethod(post);

            Header[] coockies = post.getResponseHeaders("set-cookie");
            for(Header cookie : coockies){
                buildCookie(cookie);
            }

            Header location = post.getResponseHeader("location");
            if(location != null){
                String redir  = location.getValue();
                get = new GetMethod(redir);
                get.addRequestHeader("Accept", "text/html");
                get.addRequestHeader("Connection", "keep-alive");
                get.addRequestHeader("Accept-Encoding","gzip");
                setCookies(get);
                
                client.executeMethod(get);
                resultado = getResponseBodyAsString(get);
            }else{
                throw new Exception("Login/Senha incorreto(s)");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            post.releaseConnection();
            return false;
        }

        if(resultado != null && !resultado.isEmpty() && resultado.contains("SAMLResponse")){
            return super.acsConnect(resultado,"http://auth.gazeta.pl/googleAuth/"+back);
       }
       return false;
    }

    @Override
    public String getServiceName(){
        return "a/gazeta.pl";
    }

    @Override
    public void disconnect() {
        super.disconnect();
        clearCookie();
    }


}
